<template>
  <div class="startPAE">
    <div slot="footer" class="dialog-footer clearfix">
      <div style="float: left; line-height: 32px;padding-left: 12px;">
        术前确认
        <span style='color: #999;font-size:12px;'>
          术前确认
        </span>
      </div>
      <div style="float: right;">
        <el-button type="primary" @click="submitForm('dialogLeftTop1_3_data',0)">保存</el-button>
        <el-button type="success" @click="submitForm('dialogLeftTop1_3_data',1)">确认提交</el-button>
        <el-button type="info" @click="cancel">取 消</el-button>
      </div>
    </div>
    <div class="scrollWrap" ref='scrollWrap'>
      <div class="appointmentInfoBox">
        <div class="box">
          <appointment-info :appointment='appointmentInfo'></appointment-info>
        </div>
      </div>

      <div class="pathBox margin20">
        <div class="box">
          <h3>手术路径</h3>
          <surgery-path :appointment='appointment'></surgery-path>
        </div>
      </div>
      <div class="pathBox margin20">
        <div class="box">

          <el-form :model="dialogLeftTop1_3_data" ref='dialogLeftTop1_3_data' :show-message=true :rules="appointmentConfirmConst.dialogLeftTop1_1_data_rules" :inline="true">
            <h3>
              <span>术前确认</span>
            </h3>
            <el-form-item label="主刀医生" :label-width="formLabelWidth" prop="card">
              <!--<el-input v-model="dialogLeftTop1_3_data.beforeOptConfirm.doctorId" auto-complete="off" placeholder="请输入姓名"></el-input>-->
              <el-select v-model="dialogLeftTop1_3_data.beforeOptConfirm.doctorId" filterable remote reserve-keyword placeholder="请选择"
                         :remote-method="getDoctor" :loading="loading" @change="changeDoctor">
                <el-option v-for='item in dialogLeftTop1_1_data_doctorList' :label="item.name" :value="item.id"
                           :key='item.id'></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="拟行手术" :label-width="formLabelWidth" prop="card">
              <el-select v-model="dialogLeftTop1_3_data.beforeOptConfirm.operationNo" filterable remote reserve-keyword placeholder="请选择"
                         :remote-method="getOperation" :loading="loading">
                <el-option v-for='item in operateSurgeryList' :label="item.name" :value="item.id"
                           :key='item.id'></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="拟手术日期" :label-width="formLabelWidth">
              <el-date-picker type="date" placeholder="选择日期" v-model="dialogLeftTop1_3_data.beforeOptConfirm.schedule" disabled value-format="yyyy-MM-dd HH:mm:ss" style='width: 196px;'></el-date-picker>
            </el-form-item>

            <el-form-item label="手术间" :label-width="formLabelWidth" prop="card">
              <el-input :value="dialogLeftTop1_3_data.beforeOptConfirm.subOptRoom" auto-complete="off" disabled></el-input>
            </el-form-item>

            <el-form-item label="拟接收病区" :label-width="formLabelWidth" prop="card">
              <el-select v-model="dialogLeftTop1_3_data.beforeOptConfirm.receiveArea" remote reserve-keyword placeholder="请选择"
                         :remote-method="getOrganization" :loading="loading">
                <el-option v-for='item in organizationList' :label="item.name" :value="item.id"
                           :key='item.id'></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="拟预约床位" :label-width="formLabelWidth" prop="card">
              <el-input :value="dialogLeftTop1_3_data.beforeOptConfirm.subBedNum" auto-complete="off" disabled></el-input>
            </el-form-item>

            <el-form-item label="手术台次" :label-width="formLabelWidth" prop="card">
              <el-input v-model="dialogLeftTop1_3_data.beforeOptConfirm.optNo" auto-complete="off" placeholder="请输入手术台次"></el-input>
            </el-form-item>

            <h3>
              <span>手术时间选择</span>
            </h3>
            <div class="block" v-if='weeks && weeks.length > 0'>
              <el-carousel height="150px" :autoplay=false>
                <el-carousel-item v-for="item in 4" :key="item" :autoplay=false>
                  <ul class='appointmentTimeItem'>
                    <li v-for='subItem in 7' :key='subItem' class='appointmentTime' :class='{"active": item == appointmentTimeWeek && subItem == appointmentTimeDay }' @click="selectAppointmentTime(item, subItem, weeks[item - 1]['days'][subItem - 1])">
                      <p class='myAppointment'>{{weeks[item - 1]['days'][subItem - 1]['date']}}({{weeks[item - 1]['days'][subItem - 1]['weekDay']}})
                      </p>
                      <img v-if='item == appointmentTimeWeek && subItem == appointmentTimeDay ' src="/static/tinymce4.7.5/skins/lightgray/img/appointmentTimeSelected.png" alt="">
                      <img v-else src="/static/tinymce4.7.5/skins/lightgray/img/appointmentTimeOption.png" alt="">
                    </li>
                  </ul>
                </el-carousel-item>
              </el-carousel>
            </div>

            <div>
              <el-form-item label="上午" :label-width="formLabelWidth">
                <el-radio-group v-model="am_pm_order" size="medium">
                  <el-radio v-for="index in selectDayItem.orderAmCount" :key="index" :label="selectDayItem.longDate+'_am_'+index" :disabled="includes(selectDayItem.ordered, index)" border>{{index}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="下午" :label-width="formLabelWidth">
                <el-radio-group v-model="am_pm_order" size="medium">
                  <el-radio v-for="index in selectDayItem.orderPmCount" :key="index" :label="selectDayItem.longDate+'_pm_'+index" :disabled="includes(selectDayItem.ordered, index)" border>{{index}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>

            <h3>
              <span>手术间选择</span>
            </h3>
            <div class="selectRoom">
              <el-form-item label="手术间类型" :label-width="formLabelWidth">
                <dict-select v-model="optRoomType" placeholder="请选择" style='width: 196px' dict-code="ssslb" clearable @change="getOperationRoom">
                </dict-select>
              </el-form-item>
              <div class="rooms">
                <el-form-item label="房间号" :label-width="formLabelWidth">
                  <el-radio-group v-model="dialogLeftTop1_3_data.beforeOptConfirm.subOptRoomId" size="medium" @change="changeSubOptRoom">
                    <el-radio v-for='item in optRoomList' :label="item.id" :key="item.id" border>{{item.name}}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </div>
            <h3>
              <span>床位选择</span>
            </h3>
            <div>
              <el-form-item label="病区" :label-width="formLabelWidth">
                <el-select v-model="hospitalArea" placeholder="请选择" style='width: 196px' clearable @change="queryBed()">
                  <el-option v-for='item in organizationList' :label="item.name" :value="item.id"
                             :key='item.id'></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="病房类型" :label-width="formLabelWidth">
                <dict-select v-model="bedRoomType" placeholder="请选择" style='width: 196px' clearable dict-code="bffl" @change="queryBed()">
                </dict-select>
              </el-form-item>
              <el-form-item label="床位状态" :label-width="formLabelWidth">
                <dict-select v-model="bedStatus" placeholder="请选择" style='width: 196px' clearable dict-code="bed_state" @change="queryBed()">
                </dict-select>
              </el-form-item>
              <ul class="clearfix selectBed">
                <li class=' fl' :class='{active: item.isUsed === 1}' v-for='item in bedArr' :key='item.id' @click='selectBed(item)'>
                  <p>{{item.wardName + ' ' + item.bedNo}}
                    <span>{{item.isUsed || (item.bedNo === dialogLeftTop1_3_data.beforeOptConfirm.subBedNum + '' ? 1 : 0) | isSelected}}</span>
                  </p>
                  <div class="imgBox">
                    <img v-if='item.isUsed === 0 && (item.bedNo === dialogLeftTop1_3_data.beforeOptConfirm.subBedNum + "" ? 1 : 0) === 0' src="/static/tinymce4.7.5/skins/lightgray/img/room.png" alt="">
                    <img v-else src="/static/tinymce4.7.5/skins/lightgray/img/roomSelected.png" alt="">
                  </div>
                </li>
              </ul>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import appointmentInfo from '@/yimiviews/components/appointmentInfo'
import surgeryPath from '@/yimiviews/components/path'
import _ from 'lodash'
import { appointmentConfirmConst } from '@/yimiviews/appointmentManage/columnsConst'
import { read } from '@/api/appointmentManage/appointmentConfirm'
import { getDoctorList, getOperationList, getOrganizationList } from '@/api/common/common'
import { saveSurgery, readWithAddOn as readSurgery } from '@/api/appointmentManage/surgery'
import { doctorScheduleSelect } from '@/api/knowledgeManage/doctorScheduling'
import { pending as operationRoomApi } from '@/api/knowledgeManage/operationRoom'
import { bedSelect } from '@/api/knowledgeManage/bed'
import DictSelect from '@/views/form/dictSelect'
export default {
  components: { DictSelect, appointmentInfo, surgeryPath },
  created() {
    this.getPatientInfo()
    this.weeks = this.generateDay()
    this.getDoctor(' ')
    this.getOperation(' ')
    this.getOrganization(' ')
    this.queryBed()
  },
  mounted() {
    this.setAppMainHeight()
  },
  data() {
    return {
      appointmentInfo: {},
      appointment: {
        path: 5
      },
      checkbox: [],
      appointmentTimeWeek: 1,
      appointmentTimeDay: 1,
      appointmentConfirmConst,
      dialogLeftTop1_3_data: {
        id: '',
        type: '',
        beforeOptConfirm: {
          id: '',
          appointNo: '',
          doctorName: '',
          doctorId: '',
          operationName: '',
          operationNo: '',
          operationDatetime: '',
          subOptRoom: '',
          receiveArea: '',
          subBedNum: '',
          optNo: '',
          scheduleOrder: 0
        },
        surgeryTime: {
          orderInAm: [],
          orderInPm: []
        },
        surgeryRoom: {
          roomType: '',
          rooms: []
        },
        surgeryBed: {}
      },
      formLabelWidth: '120px',
      today: '',
      weekday: '',
      weeks: [],
      bedArr: [],
      dialogLeftTop1_1_data_doctorList: [],
      loading: false,
      operateSurgeryList: [],
      organizationList: [],
      selectDayItem: {},
      includes: _.includes,
      optRoomType: null,
      hospitalArea: null,
      bedRoomType: 0,
      bedStatus: null,
      optRoomList: []
    }
  },
  methods: {
    async getPatientInfo() {
      read(this.$route.params.id).then(res => {
        this.appointmentInfo = res.data.data
      })
      const res = await readSurgery(this.$route.params.id)
      if (res.data.data) {
        const resData = res.data.data
        resData.operationNo = parseInt(resData.operationNo)
        resData.receiveArea = parseInt(resData.receiveArea)
        this.dialogLeftTop1_3_data.beforeOptConfirm = resData

        // 设置手术时间选择
        const dateStart = new Date(resData.schedule)
        const dateEnd = new Date(dateStart.getFullYear(), dateStart.getMonth() + 1, dateStart.getDate() - 1)
        const res2 = await doctorScheduleSelect({
          doctorId: resData.doctorId,
          start: resData.schedule,
          end: dateEnd.getFullYear() + '-' + (dateEnd.getMonth() + 1) + '-' + (dateEnd.getDate()) + ' 00:00:00',
          appointId: this.$route.params.id
        })
        if (resData.schedule && _.isDate(new Date(resData.schedule))) {
          const weeks = this.generateDay(dateStart)
          for (const week of weeks) {
            for (const day of week.days) {
              day.orderAmCount = 0
              day.orderPmCount = 0
              day.isUsed = 0
              day.ordered = []
              for (const schedule of res2.data.list) {
                const date = new Date(schedule.scheduleDate)
                if (day.date === (date.getMonth() + 1) + '.' + date.getDate()) {
                  if (schedule.ampmType === 0) {
                    day.ordered.push(schedule.scheduleOrder)
                    day.orderAmCount = schedule.optNo
                  } else if (schedule.ampmType === 1) {
                    day.ordered.push(schedule.scheduleOrder)
                    day.orderPmCount = schedule.optNo
                  }
                  day.isUsed = schedule.isUsed
                }
              }
            }
          }
          this.weeks = weeks
          this.selectAppointmentTime(1, 1, _(weeks).map('days').flatten().filter({ date: (dateStart.getMonth() + 1) + '.' + dateStart.getDate() }).first())
        }
        this.dialogLeftTop1_3_data.beforeOptConfirm = resData
        this.optRoomType = resData.optRoomType
        this.getOperationRoom(this.optRoomType)
      }
    },
    selectAppointmentTime(week, day, dayItem) {
      this.appointmentTimeWeek = week
      this.appointmentTimeDay = day
      this.selectDayItem = dayItem
    },
    generateDay(startDate) {
      const weekArr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      const weeks = []
      const now = startDate || new Date()
      const year = now.getFullYear()
      let weekday = now.getDay()
      let month = now.getMonth()
      let date = now.getDate()
      const endDay = new Date(year, month + 1, 0).getDate()
      month = month + 1
      for (var i = 0; i < 4; i++) {
        weeks.push({
          days: []
        })
        for (var j = 0; j < 7; j++) {
          if (date > endDay) {
            month = month + 1
            date = 1
          }
          if (weekday > 6) {
            weekday = 0
          }
          weeks[i]['days'].push({
            date: month + '.' + date,
            longDate: year + '.' + month + '.' + date,
            weekDay: weekArr[weekday]
          })
          date++
          weekday++
        }
      }
      return weeks
    },
    selectBed(item) {
      if (item.isUsed === 1 || (item.bedNo === this.dialogLeftTop1_3_data.beforeOptConfirm.subBedNum + '' ? 1 : 0) === 1) {
        return
      }
      this.$confirm('是否预约此床位?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '床位选择成功'
          })
          item.isUsed = 1
          const oldItem = _.find(this.bedArr, { bedNo: this.dialogLeftTop1_3_data.beforeOptConfirm.subBedNum + '' })
          if (oldItem) {
            oldItem.isUsed = 0
          }
          this.dialogLeftTop1_3_data.beforeOptConfirm.subBedNum = parseInt(item.bedNo)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消预约预约床位'
          })
        })
    },
    submitForm(formName, type) {
      var tipText = ['保存成功！', '提交成功！']
      this.dialogLeftTop1_3_data.id = this.$route.params.id
      this.dialogLeftTop1_3_data.type = type
      const postdata = JSON.parse(JSON.stringify(this.dialogLeftTop1_3_data))
      saveSurgery(postdata).then(res => {
        if (res.data.code === 200) {
          this.$message({
            message: tipText[type],
            type: 'success',
            duration: 2000
          })
          if (type === 1) {
            this.$root.closeTag()
          }
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    cancel() {
      this.$root.closeTag()
    },
    setAppMainHeight() {
      const bodyHeight = document.body.offsetHeight
      const appMainHeight = bodyHeight - 180
      this.$refs.scrollWrap.style.height = appMainHeight + 'px'
    },
    getDoctor(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          getDoctorList({ keyword: query.toLowerCase(), type: 1 }).then((res) => {
            this.loading = false
            this.dialogLeftTop1_1_data_doctorList = res.data.list
          })
        }, 200)
      } else {
        this.dialogLeftTop1_1_data_doctorList = []
      }
    },
    getOperation(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          getOperationList({ keyword: query.toLowerCase() }).then((res) => {
            this.loading = false
            this.operateSurgeryList = res.data.list
          })
        }, 200)
      } else {
        this.operateSurgeryList = []
      }
    },
    getOrganization(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          getOrganizationList({ keyword: query.toLowerCase(), parentId: 0 }).then((res) => {
            this.loading = false
            this.organizationList = res.data.list
          })
        }, 200)
      } else {
        this.organizationList = []
      }
    },
    getOperationRoom(val) {
      operationRoomApi({
        page: 1,
        limit: 99,
        optRoomType: val
      }).then(res => {
        this.optRoomList = res.data.list
      })
    },
    queryBed() {
      bedSelect({
        hospitalId: this.hospitalArea,
        type: this.bedRoomType,
        isUsed: this.bedStatus,
        appointId: this.$route.params.id
      }).then(res => {
        this.bedArr = res.data.list
      })
    },
    changeSubOptRoom(value) {
      this.dialogLeftTop1_3_data.beforeOptConfirm.subOptRoom = _.find(this.optRoomList, { id: value }).name
    },
    async changeDoctor(value) {
      const dateStart = new Date()
      const scheduleStr = dateStart.getFullYear() + '-' + (dateStart.getMonth() + 1) + '-' + (dateStart.getDate()) + ' 00:00:00'
      const dateEnd = new Date(dateStart.getFullYear(), dateStart.getMonth() + 1, dateStart.getDate() - 1)
      const res2 = await doctorScheduleSelect({
        doctorId: value,
        start: scheduleStr,
        end: dateEnd.getFullYear() + '-' + (dateEnd.getMonth() + 1) + '-' + (dateEnd.getDate()) + ' 00:00:00',
        appointId: this.$route.params.id
      })
      if (scheduleStr && _.isDate(new Date(scheduleStr))) {
        const weeks = this.generateDay(dateStart)
        for (const week of weeks) {
          for (const day of week.days) {
            day.orderAmCount = 0
            day.orderPmCount = 0
            day.isUsed = 0
            day.ordered = []
            for (const schedule of res2.data.list) {
              const date = new Date(schedule.scheduleDate)
              if (day.date === (date.getMonth() + 1) + '.' + date.getDate()) {
                if (schedule.ampmType === 0) {
                  day.ordered.push(schedule.scheduleOrder)
                  day.orderAmCount = schedule.optNo
                } else if (schedule.ampmType === 1) {
                  day.ordered.push(schedule.scheduleOrder)
                  day.orderPmCount = schedule.optNo
                }
                day.isUsed = schedule.isUsed
              }
            }
          }
        }
        this.weeks = weeks
        this.selectAppointmentTime(1, 1, _(weeks).map('days').flatten().filter({ date: (dateStart.getMonth() + 1) + '.' + dateStart.getDate() }).first())
      }
    }
  },
  filters: {
    isSelected(val) {
      const isSelectedBed = ['空闲', '已预约']
      return isSelectedBed[val]
    }
  },
  computed: {
    am_pm_order: {
      get() {
        const date = this.dialogLeftTop1_3_data.beforeOptConfirm.schedule || ''
        return (date.replace(' 00:00:00', '').replace(/-/g, '.') +
          (this.dialogLeftTop1_3_data.beforeOptConfirm.ampmType === 0 ? '_am_' : '_pm_') +
          this.dialogLeftTop1_3_data.beforeOptConfirm.scheduleOrder)
      },
      set(newValue) {
        if (!newValue) return
        this.dialogLeftTop1_3_data.beforeOptConfirm.ampmType = newValue.indexOf('am_') > -1 ? 0 : 1
        this.dialogLeftTop1_3_data.beforeOptConfirm.scheduleOrder = parseInt(newValue.replace(/\d+.\d+.\d+_[ap]m_/, ''))
        const date = _.first(newValue.match(/\d+.\d+.\d+/))
        if (date) this.dialogLeftTop1_3_data.beforeOptConfirm.schedule = date.replace(/./g, '-') + ' 00:00:00'
      }
    }
  },
  watch: {
    'dialogLeftTop1_3_data.beforeOptConfirm.doctorId': function() {
      try {
        this.dialogLeftTop1_3_data.beforeOptConfirm.doctorName = this.dialogLeftTop1_3_data.beforeOptConfirm.doctorId !== ''
          ? _.find(this.dialogLeftTop1_1_data_doctorList, { id: this.dialogLeftTop1_3_data.beforeOptConfirm.doctorId }).name : ''
      } catch (e) {
        console.log(e)
      }
    },
    'dialogLeftTop1_3_data.beforeOptConfirm.operationNo': function() {
      try {
        this.dialogLeftTop1_3_data.beforeOptConfirm.operationName = this.dialogLeftTop1_3_data.beforeOptConfirm.operationNo !== ''
          ? _.find(this.operateSurgeryList, { id: this.dialogLeftTop1_3_data.beforeOptConfirm.operationNo }).name : ''
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>
<style lang="scss">
.startPAE {
  padding-bottom: 20px;
  background-color: #f0f2f5;
  .margin20 {
    margin: 20px;
    background-color: #fff;
  }
  .box {
    padding: 20px;
  }
  .scrollWrap {
    min-height: 100%;
    overflow: auto;
  }
  .dialog-footer {
    padding: 10px;
    background-color: #fff;
    margin-bottom: 20px;
  }
  .appointmentInfoBox {
    background-color: #fff;
    padding: 0 20px;
  }
  .el-carousel__container {
    padding: 0 30px;
    height: 110px !important;
    .appointmentTimeItem {
      display: flex;
      padding-bottom: 20px;
      border-bottom: 1px dashed #ddd;
      .appointmentTime {
        flex: 1;
        position: relative;
        list-style: none;
        text-align: center;
        cursor: pointer;
        &:after {
          display: block;
          content: "";
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          top: 65px;
          width: 10px;
          height: 10px;
          border-radius: 50%;
          border: 1px solid #ddd;
        }
        &.active {
          color: #fff;
        }
        &.active:after {
          background: #409eff;
        }
        .myAppointment {
          position: absolute;
          padding: 0;
          margin: 0;
          width: 100%;
          height: 100%;
          line-height: 38px;
          text-align: center;
          z-index: 20;
        }
      }
    }
  }
  .morning {
    flex: 1;
    margin: 0 20px;
    height: 38px;
    line-height: 38px;
    border: 1px solid #ddd;
    text-align: center;
    list-style: none;
  }
  h4 {
    margin: 0 0 10px 60px;
  }
  .selectRoom {
    li {
      cursor: pointer;
      position: relative;
      i.el-icon-success {
        position: absolute;
        right: -5px;
        bottom: -5px;
        &.active {
          color: #409eff;
        }
      }
    }
  }
  .selectBed {
    li {
      width: 23%;
      list-style: none;
      margin: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      cursor: pointer;
      p {
        margin: 0;
        padding: 15px;
        border-bottom: 1px solid #ddd;
        span {
          float: right;
          margin-right: 10px;
          &:before {
            display: inline-block;
            content: "";
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #ddd;
            margin-right: 10px;
          }
        }
      }
      &:hover {
        border-color: #409eff;
        p {
          border-bottom-color: #409eff;
        }
      }
      &.active {
        border-color: #409eff;
        p {
          color: #409eff;
          border-bottom: 1px solid #409eff;
          span {
            &:before {
              background: #409eff;
            }
          }
        }
      }
    }
    .imgBox {
      width: 100%;
      height: 150px;
      line-height: 150px;
      text-align: center;
      img {
        width: 70%;
        vertical-align: middle;
      }
    }
  }
}
</style>

